/*
 * Assignment02.c
 *
 * Created: 3/3/2015 12:31:35 PM
 *  Author: Jeevake Attapattu
 */


#include <avr/io.h>
#include <avr/interrupt.h>

void toggleLED(void)
{
		TCNT1 = 34286;//2^16 - 0.25*8MHz/64
		TCCR1A = 0x00;
		TCCR1B = 0x03;//use pre-scalar of 64
		while ((TIFR1&0X01)==0)//wait for overflow
		{
		}
		TCCR1B = 0x00;//clear overflow flag
		TIFR1 = 1<<TOV1;
		PORTB = PORTB^(1<<5);//toggle B5
}


int main(void)
{
		int counter = 0;
		int fiver = 0;
		DDRB = 1 << 5|1 << 4;//set pins B5 & B4 to output set pin B0 to input
		
		PORTB &= ~(1<<5);
		PORTB &= ~(1<<4);
		DDRD = 0xFF; //set all port D to output;
		PORTD &= 0x00;
		TIMSK0 = (1<<TOIE0);//set interrupt timer mask register
		sei(); //enable interrupts
		while(1)
		{
				toggleLED();
				counter++;//increment 8 bit counter
				PORTD = counter;//display 8bit counter
				if(fiver%10==0)//check if 5 rising edges have passed
				{
						TCNT0 = 254;//start value for timer0
						TCCR0A = 0x00;
						TCCR0B = 0x05;//use pre-scalar of 1024
				}
				fiver++;//increment B4 counter
		}
		return 0;
}

ISR (TIMER0_OVF_vect)//use overflow of timer0 interrupt
{
	TCCR0B = 0x00;//stop timer
	TIFR0 = 1<<TOV0;//clear overflow flag
	PORTB = PORTB^(1<<4);//toggle B4
}
